/*
 * @Author: Wxx
 * @Date: 2022-02-22 17:47:53
 * @LastEditors: Wxx
 * @LastEditTime: 2022-02-22 17:58:12
 * @Description:
 */
import { useEffect, useMemo, useState } from "react";
import axios from "axios";

/**
 * 自定义 Hook 是一个函数，其名称以 “use” 开头，函数内部可以调用其他的 Hook
 * 自定义hooks其实就是把复杂的逻辑抽离成函数用use开头命名
 */
function useCinemasList() {
  const [cinemasList, setCinemasList] = useState([]);

  useEffect(() => {
    axios({
      url: "https://m.maizuo.com/gateway?cityId=610900&ticketFlag=1&k=2285502",
      headers: {
        "X-Host": "mall.film-ticket.cinema.list",
        "X-Client-Info":
          '{"a":"3000","ch":"1002","v":"5.2.0","e":"16454281163713789501374465","bc":"110100"}',
      },
    }).then((res) => {
      setCinemasList(res.data.data.cinemas);
    });
  }, []);
  return {
    cinemasList,
  };
}

function useFilterCinemas(cinemasList, text) {
  // 类似于vue中的计算属性
  const getFilterList = useMemo(
    () =>
      cinemasList.filter(
        (item) =>
          item.name.toUpperCase().includes(text.toUpperCase()) ||
          item.address.toUpperCase().includes(text.toUpperCase())
      ),
    [cinemasList, text]
  );
  return {
    getFilterList,
  };
}

export default function Cinemas() {
  const [text, setText] = useState("");

  const { cinemasList } = useCinemasList();
  const { getFilterList } = useFilterCinemas(cinemasList, text);
  const handleChange = (e) => {
    setText(e.target.value);
  };

  return (
    <div>
      <input value={text} onChange={handleChange} />
      {getFilterList.map((item) => (
        <div key={item.cinemaId} style={{ borderBottom: "1px solid #eee" }}>
          <h4>{item.name}</h4>
          <p style={{ fontSize: 12 }}>{item.address}</p>
        </div>
      ))}
    </div>
  );
}
